<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        /**
         *  localStorage
         * 
         */

        localStorage.setItem('username', 'yuonly');
        localStorage.setItem('sex','girl');
        // sessionStorage.setItem('age', 100);

        // 读取
        let res = localStorage.getItem('username')
        console.log(res);

        // 删除
        // localStorage.removeItem('username');

        // 全删
        localStorage.clear();

        // 存储数据类型说明
        let todos = [
            {
                id:1,
                title:'吃饭',
                isDone:true
            }
        ]
        // 如果直接把数组对象存入 localStorage，数据会变成一个 object Object的字符串
        // localStorage.setItem('todos', todos);
        // let todosStr = localStorage.getItem('todos');
        // console.log(todosStr, typeof todosStr);  // [object Object] string

        // 如果要将对象或数组存入localStorage ，需要先转化为Json格式的字符串，在存
        // 读取恢复数据，JSON.parse 还原成原来的数组或对象
        
        localStorage.setItem('todos', JSON.stringify(todos));

        let jsonStr = localStorage.getItem('todos'); // string
        console.log(jsonStr, typeof jsonStr);

        let json = JSON.parse(jsonStr);
        console.log(json, typeof json);
        console.log(json[0].title);

        // 当读取一个localStorage中不存在的key的值的时候
        let result = JSON.parse(localStorage.getItem('sdjfkljlk'))
        console.log(result);

    </script>
</body>
</html>